const Koa = require("koa")
const app = new Koa()
const WebSocket = require("ws")
const wsServer = WebSocket.Server
const bodyParser = require("koa-bodyparser")

app.use(async (ctx, next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    var
        start = new Date().getTime(),
        execTime;
    await next();
    execTime = new Date().getTime() - start;
    ctx.response.set('X-Response-Time', `${execTime}ms`);
})

app.use(bodyParser())

let server = app.listen(4000, () => {
    console.log('服务启动成功')
})

const wss = new wsServer({
    server: server
})
// 模拟数据库存储用户信息
const data = [
    {
        name: "张三",
        id: "1001"
    },
    {
        name: "李四",
        id: "1002"
    },
    {
        name: "王五",
        id: "1003"
    }
]
// 在线用户
let users = []
// 在线人数
let online = 0

// 广播
wss.broadcast = function (data) {
    let msgObj = JSON.stringify(data)
    wss.clients.forEach(function each(client) {
        // 向所有客户端广播消息，包括自己 client === ws，不包括自己 client !== ws
        if (client.readyState === WebSocket.OPEN) {
            client.send(msgObj);
        }
    });
}

wss.on("connection", function (ws, req) {
    const ip = req.connection.remoteAddress;
    // 获取当前在线人数
    online = wss._server._connections
    console.log("当前在线人数: ", online, "提取网址参数: ", req.url, "连接的ip是：", ip)
    const id = req.url.split("/")[1]
    // 查询id对应的用户
    const u = data.filter(item => item.id === id)[0]
    if (u) {
        // 添加到在线用户
        if (!users.some(item => item.id === id)) {
            users.push({
                ...u,
                ws: ws
            })
        }
        // console.log("users", users)
    } else {
        users.push({
            name: "游客" + id,
            id: id,
            ws: ws
        })
    }

    ws.on("message", function(message) {
        let obj = JSON.parse(message)
        // console.log("type", obj.type, "message", obj.msg)
        // 向指定用户发送消息发送消息
        if (obj.type === "chat") {
            // 表示该消息为聊天类型
            const Index = users.findIndex(item => item.id === obj.to)
            users[Index].ws.send(JSON.stringify(obj))
        } else if (obj.type === "connect"){
            // 用户连接成功， 通知所有人
            const cur = users.filter(item => item.id === id)[0]
             // 查询数据库返回对应用户
            // const list = JSON.parse(JSON.stringify(users))
            const list = users.map(item => {
                return {
                    name: item.name,
                    id: item.id
                }
            })
            let msgObj = {
                userList: list,
                online: online,
                type: "sys_notif",
                msg: cur.name + "进入聊天室了"
            }
            // console.log("msgObj", msgObj)
            wss.broadcast(msgObj)
        }
        
    })
    // 断开连接回调
    ws.on("close", function (event, reason) {
        online = wss._server._connections
        const delUser = users.filter(item => item.id === id)[0]
        users = users.filter(item => item.id !== id)
        const tempList = users.map(item => {
            return {
                name: item.name,
                id: item.id
            }
        })
        const data = {
            type: "sys_notif",
            userList: tempList,
            online: online,
            msg: "用户" + delUser.name + "退出鸟"
        }
        wss.broadcast(data)
    })
})


